<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%String path = request.getContextPath() ;%>
<%@ taglib uri="/WEB-INF/tld/c.tld" prefix="c" %> 
<%@ taglib uri="/WEB-INF/tld/ui.tld" prefix="ui" %> 
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
 <meta name="renderer" content="webkit">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>客户开票申请列表</title>
<jsp:include page="../../import.jsp" flush="true" />
</head>
<body class="iframeBody">
<div class="Wrapper">
<div class="searchArea">
    <form id="searchBar">
        <div class="fieldset1 clearFix">
            <div class="fieldBox" id="searchPrjNmId">
                <div class="label">申请时间</div>
                <div class="field">
                    <input name=applyTm id="applyTm" type="text" class="ui-datepicker" readonly="readonly" value="">
                </div>
            </div>
            <div class="fieldBox" id="searchCstMgrNmId">
                <div class="label">申请人</div>
                <div class="field">
                    <input name="cstMgrNm" id="cstMgrNm" type="text" class="ui-textbox" value="">
                </div>
            </div>
            <div class="fieldBox" id="searchRcverNmId">
                <div class="label">收件人</div>
                <div class="field">
                    <input name="rcverNm" id="rcverNm" type="text" class="ui-textbox" value="">
                </div>
            </div>
           <div class="fieldBox" id="searchCstNmId">
                <div class="label">客户名称</div>
                <div class="field">
                    <input name="cstNm" id="cstNm" type="text" class="ui-textbox" value="">
                </div>
            </div>
            <div class="fieldBox" id="searchPaySchNoId">
                <div class="label">支付表号</div>
                <div class="field">
                    <input name="paySchNo" id="paySchNo" type="text" class="ui-textbox" value="">
                </div>
            </div>
            <!-- hide data -->
		    <div class="fieldBox" style="display:none;">
				 <div class="field">
				    <input name="extPaySchMId" id="extPaySchMId" type="text" class="ui-textbox" value="${extPaySchMId}">
				    <input name="extPrjId" id="extPrjId" type="text" class="ui-textbox" value="${extPrjId}">
			     </div>
			</div>
            <div class="clearFix"></div>
	        <div class="btnsBox formBtns notRight">
	             <span id="searchBtn" class="sq-button-round">查询</span>
	             <span id="clearBtn" class="sq-button-round">清空</span>
	               
	             <span id="applyInvoiceBtn" onclick="applyInvoice('2');" class="sq-button-round">申请纸质发票</span>
                 <span id="applyEInvoiceBtn" onclick="applyInvoice('1');" class="sq-button-round">申请电子发票</span>
	             <input id="resetBtn" type="reset" value="重置" class="l-button l-button-reset Hide"/>
	        </div>
        </div>
    </form>
</div>
<!-- 开票申请列表 -->
<div id="invoiceApplyGrid" class="sq-grid"></div> 
</div>

<script type="text/javascript">
    var grid = null, menu = null;
    $(function () {
        grid = $("#invoiceApplyGrid").ligerGrid({
            url: '<%=path%>/invoice/prjbillapply/initList.do',
            delayLoad:true,
            method: 'get',
            columns: [
                {display: '申请时间', name: 'applyTm', width: 140, align: 'center', enabledSort: false,
                	render:function (rowdata, rowindex, value, column) { 
                		var time = DateUtils.formatDateToString(value, DateUtils.YYYY_MM_DDHHMMSS);
                		var h = '';
            		    h='<a  href="javascript:showDetail(';
                        h+="'"+rowdata.id+"'";
                        h+=",'"+rowdata.billWayCd+"'";
                        h+=')">'+time+'</a>'
                        return h;
            		}
                },
                {display: '申请人', name: 'cstMgrNm', width: 80, align: 'center', enabledSort: false},
                {display: '客户名称', name: 'cstNm', width: 120, align: 'center', enabledSort: false,
                	render: function (rowdata, rowindex, value){
                		if(StringUtils.isEmpty(value)){
	                		value = "";
	                	}
	            		var h = '';
	            		    h='<a href="javascript:showCustomsDetail(';
	                        h+="'"+rowdata.cstId+"'";
	                        h+=')">'+value+'</a>'
	                        return h;
                    }
                },
                {display: '收件人', name: 'rcverNm', width: 80, align: 'center', enabledSort: false},
                {display: '收件地址', name: 'rcvAddr', width: 150, align: 'center', enabledSort: false,
                	render: function (rowdata, rowindex, value){
                		return UIUtils.showColumnTip(value);
                    }
                },
                {display: '联系电话', name: 'rcverTel', width: 100, align: 'center', enabledSort: false},
                {display: '开具方式', name: 'billWayCdNm', width: 100, align: 'center', enabledSort: false},
                {display: '开票状态', name: 'audStsCdNm', width: 100, align: 'center', enabledSort: false},
                {display: '快递公司', name: 'expCorp', width: 100, align: 'center', enabledSort: false,
                	render: function (rowdata, rowindex, value){
                		return UIUtils.showColumnTip(value);
                    }
                },
                {display: '快递单号', name: 'trcNo', width: 110, align: 'center', enabledSort: false},
                {display: '流程编号', name: 'pno', width: 150, align: 'center', enabledSort: false,
                	 render: function (rowdata, rowindex, value){
                		 var h = '';
	             		     h='<a  href="javascript:commShowFlow(';
	                         h+="'"+rowdata.pinstId+"'";
	                         h+=",'"+rowdata.audStsCd+"'";
	                         h+=",'"+rowdata.id+"'";
	                         h+=')">'+UIUtils.showColumnTip(value)+'</a>'
                         return h;
                     }
				}/* ,
                {display: '流程实例ID', name: 'pinstId', width: 110, align: 'center', enabledSort: false,
					 render: function (rowdata, rowindex, value){
						 return UIUtils.showColumnTip(value);
		             }
				} */,
                getGridOperColumnContent()
            ],
            pageSize: 10,
            root: 'rows',
            record: 'total',
            hideLoadButton: true,
            width: '100%',
            height: '100%',
            heightDiff: -2,
            rownumbers:true,
            frozen: false,
            allowUnSelectRow: true,
            alternatingRow: false,
            onBeforeShowData: function ()
            {
                var grid = this;
                grid.collapsedRows = [];
            },
            isShowDetailToggle:function (row)
            {
            	if(row.audStsCd == CommonConstant.C_AUD_NO_HAPPEN_CODE || 
            			row.audStsCd == CommonConstant.C_AUD_ADNWAY_CODE){
            		return false;
            	}
            	return true;
            },
            detail: {
                height: 'auto',
                onShowDetail: showDetail_grid
            }
        });
        grid.setHeight(100);

        $("#searchBar").ligerForm();
        
        reLoadGrid();//加载Grid

        $("#pageloading").hide();

        /* 查询 */
        $("#searchBtn").click(function (event) {
        	reLoadGrid();
        });

        /* 清空 */
        $("#clearBtn").click(function (event) {
            $("#resetBtn").click();  //重置 input-text
        });
        
        initForm();
    });
    
  	//查看客户详情数据
	function showCustomsDetail(_id){
		parent.mainApp.f_addTab('tab_customer_np_detail'+_id,'客户详情','<%=path%>/customer/cstbscinfo/toCustDetailPage.do?id='+_id);
	}
  	
  	//显示流程
    function commShowFlow(_pInstId, _audStsCd, _businessKey){
    	if(StringUtils.isEmpty(_pInstId)){
    		UIUtils.alertWarning(CommonConstant.C_P_INSTANCEID_NOT_HERE);
    		return;
    	}
    	var _formUrl = "/invoice/prjbillfeer/toAuditingDetailPage.do?id=";
    	var params = "?pInsId="+_pInstId+"&status="+_audStsCd+"&businessKey="+_businessKey+"&formUrl="+_formUrl;
    	Add_navTab('tab_cst_invoice_flow_'+_businessKey,'查看流程',"<%=path%>/flow/flow/toFlowShowPageFowBus.do"+params);
    }
    
    //重新加载Grid
    function reLoadGrid(){
    	var form = liger.get("searchBar");
        var data = form.getData();
        for (name in data) {
            grid.setParm(name, data[name]);
        }
        grid.setParm("isAuth", "1");
        
        grid.reload();
    }

    
    //初始化Form
    function initForm(){
		ligerPersonForm = $("#div_invoice_apply_valid_form").ligerForm({
         	 validate: true
  		});
    }

    //逾期明细列表
    function showDetail_grid(row, detailPanel, callback){
        var gridBox = document.createElement('div');
        $(gridBox).css('margin', 10);
        $(detailPanel).css({
            'padding': 10,
            'box-sizing': 'border-box'
        }).append(gridBox);
        detailGrid = $(gridBox).ligerGrid({
            url: '<%=path%>/invoice/prjbillfeer/initList.do?applyId='+row.id,
            method: 'get',
            columns: [
                {display: '业务模式', name: 'bizTypCdNm', width: 180, align: 'center'},
                {display: '支付表号',name: 'paySchNo',width: 180,align:'center',
                	render: function (rowdata, rowindex, value, column) { 
	            		var h = '';
	            		    h='<a href="javascript:detailBtn(';
	                        h+="'"+rowdata.id+"',";
	                        h+="'"+rowdata.paySchId+"',";
	                        h+=')">'+value+'</a>'
	                        return h;
	            		},
                },
                {display: '费用项',name: 'feeTypCdNm',width: 150,align:'center'},
                {display: '开票金额(元)',name: 'billAmt', width: 100,align:'right',
	                render:function(rowdata,index,value){
	                    return '&yen;' + FormatMoney(rowdata.billAmt/100);
	                }
	            },
                {display: '票据类型', name: 'billTypCdNm', width: 180, align: 'center'},
                {display: '票据状态', name: 'billStsCdNm', width: 180, align: 'center'},
                {display: '发票号', name: 'billNo', width: 180, align: 'center'},
                {display: '发票流水号', name: 'serialNo', width: 180, align: 'center'},
            ],
            root: 'rows',
            hideLoadButton : true,
            width: '100%',
            height: 'auto',
            isScroll: false,
            rownumbers:true,  //显示序号
            allowUnSelectRow:true,
            alternatingRow: false,
            onAfterShowData: callback,
            frozen: false,
            usePager: false
        });
    }
    
  	//查看支付表详情
    function detailBtn(id,paySchId){
    	var editFlag = true;
    	Add_navTab('tab_prj_quat_prps'+id,'查看支付表','<%=path%>/project/prjprdpayschm/toPrjPrdPaySchMDetailPageBySchId.do?paySchId='+paySchId);
     }
    
    //获取Grid操作列内容
    function getGridOperColumnContent(){
    	 var data = {
            display: '操作',
            isSort: false,
            align:'left',
            width: 200,
            render: function (rowdata, rowindex, value){
            	//如果申请单状态为未提交则可以修改、可以删除、申请开票
            	var h= "";
            	// 纸质发票
            	if ("2" == rowdata.billWayCd) {
                    if (rowdata.audStsCd == FlowConstant.FLOW_CHECK_STATE_NON) {//待提交
                        //如果是正常的则显示发起,不是正常的则不能显示发起流程
                        if (rowdata.rlFlowCd == FlowConstant.FLOW_BILL_APPLY_RL_FLOW_CD_NORMAL) {
                            h += '<a class="sq-button-hasicon" alt="发起流程" href="javascript:applyFlowRow(';
                            h += "'" + rowdata.id + "'";
                            h += ",'" + rowdata.cstId + "'";
                            h += ",'" + rowdata.cstNm + "'";
                            h += ")\"><i class=\"sqBtnIco_47\"></i>" + LogUtils.LOG_CUST_APPLY_INVOICE_NEW + "</a>";
                        }
                        h += '<a  class="sq-button-hasicon" alt="修改" href="javascript:modifyRow(';
                        h += "'" + rowdata.id + "'";
                        h += ")\"><i class=\"sqBtnIco_4\"></i>" + LogUtils.LOG_CMM_GRID_BTN_MODIFY + "</a>"

                        h += '<a class="sq-button-hasicon" alt="删除" href="javascript:delRow(';
                        h += "'" + rowdata.id + "'";
                        h += ")\"><i class=\"sqBtnIco_7\"></i>" + LogUtils.LOG_CMM_GRID_BTN_DELETE + "</a>";
                    } else if (rowdata.audStsCd == FlowConstant.FLOW_CHECK_STATE_NO_PASS) {//审核不通过
                        /* 	h+='<a class="sq-button-hasicon" alt="发起流程" href="javascript:applyFlowRow(';
                            h+="'"+rowdata.id+"'";
                            h+=")\"><i class=\"sqBtnIco_47\"></i>"+LogUtils.LOG_CUST_APPLY_INVOICE_NEW+"</a>"; */
                    } else if (rowdata.audStsCd == FlowConstant.FLOW_CHECK_STATE_IN) {
                        /* h+='<a  class="sq-button-hasicon" alt="修改" href="javascript:modifyRow(';
                     h+="'"+rowdata.id+"'";
                     h+=")\"><i class=\"sqBtnIco_4\"></i>"+LogUtils.LOG_CMM_GRID_BTN_MODIFY+"</a>" */
                    }
                } else if ("1" == rowdata.billWayCd) {
                    // 电子发票
                    h += '<a  class="sq-button-hasicon" alt="重新推送" href="javascript:toPushAgainPage(';
                    h += "'" + rowdata.id + "'";
                    h += ")\"><i class=\"sqBtnIco_21\"></i>重新推送</a>"
                }
                return h;
            }
    	 }
    	return data;
    }

    // 到重新推送页面
    function toPushAgainPage(applyId) {
        var onOk = function (item, Dialog) {
            if (Dialog.onOk) Dialog.onOk();
        };
        var onCancel = function (item, Dialog) {
            Dialog.hide();
        };
        $.ligerDialog.open({
            title: '重新推送',
            width: 400,
            height: 180,
            url: '<%=path%>/invoice/electron/toPushAgainPage.do?applyId=' + applyId,
            buttons: [
                {
                    text: "确认推送", cls: 'l-dialog-btn-ok', onclick: onOk
                }, {
                    text: "取消", cls: 'l-dialog-btn-no', onclick: onCancel
                }
            ]
        });
    }

    //申请开票
    function applyFlowRow(_id, _cstId, _cstNm){
        var modelTyp = FlowConstant.FLOW_MODEL_TYP_INVOICE;  //流程业务类型:开票
        if(StringUtils.isEmpty(modelTyp)){
        	console.log("modelTyp is null");
        	return;
        }
        //验证数据状态
        var flowDialog = $.ligerDialog.SQopen({
            url: '<%=path%>/flow/flow/toForStartListPage.do',
            urlParms:{modelTyp:modelTyp},
            width: 700,
            height:400,
            title : '请选择要发起的流程',
            buttons: [{
	                text: "确定", type: 'ok', cls: 'sq-button sq-button-round',
	                onclick: function (item, Dialog) {
	                    if (Dialog.onOk) Dialog.onOk();
	                }
	            }, {
	                text: "取消", type: 'cancel', cls: 'sq-button sq-button-round',
	                onclick: function (item, Dialog) {
	                    if (Dialog.onCancel) Dialog.onCancel();
	                }
	            }
	        ],
            onClose: function () {
            	var json = flowDialog._DATA;
            	if(!json){
                	return;
            	}
            	var formData = {};
            	formData["procDefKey"] = json.procDefKey;
	    		formData["procDefId"] = json.procDefId;
	    		formData["procNo"] = json.procNo;
	    		formData["id"] = _id;
	    		formData["cstId"] = _cstId;
	    		formData["cstNm"] = _cstNm;
	    		//alert(JSON.stringify(formData));
	    		//return;
	    		var _url = '<%=path%>/invoice/prjbillapply/addFlowStartNormal.do';
	    		AjaxUtils.ajaxPost(_url, formData, function(msg){
	    			if(msg.success == 1){
	       				 if(msg.data){
                             alertNextFlowAssign(msg.data);
	       				 }else{
	       					 UIUtils.alertSuccess(msg.info);
	       				 }
	       				 grid.reload();
	       			 }else{
	       				 UIUtils.alertError(msg.info);
	       			 }
				},true);
            }
        });
    }
    
    //修改
    function modifyRow(_id){
    	var params = "?id="+_id;
		Add_navTab('tab_invoice_modify_apply_'+_id,'修改发票','<%=path%>/invoice/prjbillapply/toModifyPage.do'+params,function(){
			grid.reload();	
		});
    }
    
    //作废
    function delRow(_id){
   		$.ligerDialog.confirm(LogUtils.LOG_CMM_DELETE_CONFIRM, function (flag) {
   			if(flag == false)return;
   		 		var url = '<%=path%>/invoice/prjbillapply/deleteById.do';
         		AjaxUtils.ajaxPost(url, {id:_id}, delRowCallback);
   		});
    }
    
    //作废回调
    function delRowCallback(msg){
    	if(msg.success == 1){
				UIUtils.alertSuccess(msg.info);
				grid.reload();
		}else{
				UIUtils.alertWarning(msg.info);
		}
    }
    
	//选择客户页面
	function applyInvoice(flag){
		//弹出一个窗口
		$.ligerDialog.SQopen({
            title : '申请开票',
            width: 800,
            height:500,
            //top: 100,
            url:'<%=path%>/customer/cstbscinfo/toPublicCompListPage.do?multiRow='+false,
            // 自定义buttons的时候 不要设置 fixButtons: true
            buttons: [
                {
                    text: "确定", cls: 'l-dialog-btn-ok', onclick:function(item, Dialog){
                    	//点击确定获取到选中的人,然后跳转到申请开票主页面, 如果没有获取到人则提示
                    	if (Dialog.onOk) {
                    		var cstMap = Dialog.onOk();
                    		//alert(JSON.stringify(cstMap));
                    		var kv = cstMap.keySet();
                    		//alert(JSON.stringify(kv));
                    		//alert(cstMap.get(kv[0]));
                    		var cstId = kv[0];
                    		if(StringUtils.isNotEmpty(cstId)){
                    			var cstNm = cstMap.get(cstId);
                    			//关闭窗口
                    			Dialog.close();
                    			//调转到新增页面
                    			applyAdd(cstId, cstNm, flag);
                    		}else{
                    			UIUtils.alertWarning("未选择到客户信息,不能操作!");
                    		}
                    	}
                    }
                }, {
                    text: "取消", cls: 'l-dialog-btn-no', onclick:function(item, Dialog){
                    	if (Dialog.onCancel) {
                    		Dialog.onCancel();
                    	}
                    }
                }
            ]
        });
	}
	
	
	//调转到申请页面
	function applyAdd(_cstId, _cstNm, flag){
		var params = "?cstId="+_cstId+"&cstNm="+_cstNm+"&flag="+flag;
		if ("2" == flag) {
		    // 纸质发票
            Add_navTab('tab_cst_invoice_apply_add_' + _cstId + flag, '申请开票-' + _cstNm, '<%=path%>/invoice/prjbillapply/toInvoiceApplyAddPage.do' + params, applyAddCallback);
        } else if ("1" == flag) {
		    // 电子发票
            Add_navTab('tab_cst_invoice_apply_add_' + _cstId + flag, '申请开票-' + _cstNm, '<%=path%>/invoice/electron/toApplyPage.do' + params, applyAddCallback);
        }
	}
	
	//新增回调
	function applyAddCallback(){
        reLoadGrid();
	}
	
	// 展示详情
	function showDetail(_id, flag){
        var url;
        // flag = "2";
        if ("1" == flag) {
            // 电子详情
            url = '<%=path%>/invoice/electron/toDetailPage.do';
        } else if ("2" == flag) {
            // 纸质详情
            url = '<%=path%>/invoice/prjbillfeer/toAuditingDetailPage.do';
        }
        // 弹出一个窗口
        $.ligerDialog.SQopen({
            title: '申请详情',
            width: 1000,
            height: 400,
            url: url,
            urlParms: {id: _id, isGetUrl: '1'},
            // 自定义buttons的时候 不要设置 fixButtons: true
            buttons: [
                {
                    text: "关闭", onclick: function (item, Dialog) {
                        if (Dialog.onCancel) {
                            Dialog.onCancel();
                        }
                    }
                }
            ]
        });
    }
	
    //格式化时间
    function renderDate(rowdata, index, value) {
        var dateStr = "";
        if (null != value) {
            var date = new Date(value);
            dateStr = DateUtils.formatDate(date, DateUtils.YYYY_MM_DDHHMMSS);
        }
        return dateStr;
    }

    function alertNextFlowAssign(key) {
        var url = '<%=path%>/flow/flow/getFlowNextAssigne.do?key=' + key;
        var wait_dialog = $.ligerDialog.SQalert({
            content: LogUtils.LOG_CMM_DATA_LOADING,
            SQ_type: "waitting",
            onClose: function () {
            }
        });
        setTimeout(function () {
            $.ajax({
                type: 'post',
                dataType: 'json',
                url: url,
                success: function (msg) {
                    wait_dialog.close();
                    if (msg.success == 1) {//成功发起流程
                        $.ligerDialog.SQalert({
                            SQ_showButtons: true,
                            SQ_onBtnclick: function (item, Dialog) {
                                //关闭当前Tab
                                Remove_navTab();
                                frameElement.dialog.close();
                            },
                            content: msg.info
                        });
                    } else if (msg.success == 0) {//错误
                        UIUtils.alertErrorHold1(msg.info);
                    }
                }
            });
        }, 8000);
    }
</script>

</body>
</html>